package com.likai.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.likai.entry.WeatherResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 天气数据实现类
 */
@Service
public class WeatherDataServiceImpl implements com.likai.service.WeatherDataService {
    /** logger */
    private static final Logger LOGGER = LoggerFactory.getLogger(WeatherDataServiceImpl.class);
    //接口地址
    private static final String WEATHER_URI = "http://wthrcdn.etouch.cn/weather_mini";
    //超时时间
    private static final long TIME_OUT = 1800L;

    //springboot提供的rest接口api
    @Autowired
    private RestTemplate restTemplate;

    //redis提供的api
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public WeatherResponse getDataByCityId(String cityId) {
        String url = WEATHER_URI + "?citykey=" + cityId;
        return this.doGetWeather(url);
    }

    @Override
    public WeatherResponse getDataByCityName(String cityName) {
        String url = WEATHER_URI + "?city=" + cityName;
        return this.doGetWeather(url);
    }

    @Override
    public void syncDataByCityId(String cityId) {
        String url = WEATHER_URI + "?citykey=" + cityId;
        this.saveWeatherData(url);

    }

    /**
     * 发送get请求获取天气数据
     * @param url
     * @return
     */
    private WeatherResponse doGetWeather(String url) {
        String strBody = null;
        //实例化ValueOperations对象
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        //先查询缓存 使用url作为key
        if (stringRedisTemplate.hasKey(url)) {
            LOGGER.info(" redis has data");
            strBody = ops.get(url);

        } else {
            ResponseEntity<String> respString = restTemplate.getForEntity(url, String.class);
            if (respString.getStatusCodeValue() == 200) {
                strBody = respString.getBody();
            }

            LOGGER.info(" redis not has data");
            //把数据写入缓存
            ops.set(url,strBody,TIME_OUT, TimeUnit.SECONDS);

        }
        WeatherResponse resp = null;
        ObjectMapper mapper = new ObjectMapper();
        try {
            resp = mapper.readValue(strBody,WeatherResponse.class);
        } catch (IOException e) {
            LOGGER.error("Error",e);
        }

        return resp;
    }

    /**
     * 保存天气数据到redis中
     * @param url
     */
    private void saveWeatherData(String url) {
        String strBody = null;
        //实例化ValueOperations对象
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ResponseEntity<String> respString = restTemplate.getForEntity(url, String.class);
        if (respString.getStatusCodeValue() == 200) {
            strBody = respString.getBody();
        }

        //把数据写入缓存
        ops.set(url,strBody,TIME_OUT, TimeUnit.SECONDS);
    }

}
